package util

import (
	"math"
	"math/big"
	"strconv"

	"github.com/leekchan/accounting"
	"github.com/shopspring/decimal"
)

func ToFix(f float64, fix int) string {
	return strconv.FormatFloat(f, 'f', fix, 64)
}

// ThousandNumber 千分位格式化数字， fix为保留的小数位数
func ThousandNumber(f float64, fix int) string {
	return accounting.FormatNumber(f, fix, ",", ".")
}

// 比较两个浮点数的大小，解决精度问题。识差在0.000000000001 之内，认为是相等的
// !! 如果其中有一个是NaN, 则返回0
func Compare(x, y float64) int {
	if math.IsNaN(x) || math.IsNaN(y) {
		return 0
	}

	xx := big.NewFloat(x)
	yy := big.NewFloat(y)
	diff := new(big.Float).Sub(xx, yy)
	abs := new(big.Float).Abs(diff)
	if abs.Cmp(big.NewFloat(0.000000000001)) < 0 {
		return 0
	}

	if diff.Cmp(big.NewFloat(0)) > 0 {
		return 1
	}

	return -1
}

func ToPercent(n decimal.Decimal) string {
	return n.Mul(decimal.NewFromInt(100)).StringFixed(2) + "%"
}

func Float64ToPercent(f float64) string {
	n := decimal.NewFromFloat(f)
	return n.Mul(decimal.NewFromInt(100)).StringFixed(2) + "%"
}
